package com.example.common.dialog;

import com.example.common.ResourceTable;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.element.FrameAnimationElement;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;

public class LoadingDialog {

    private FrameAnimationElement loadingAnim;
    private CommonDialog loadingDialog;

    public void show() {
        if (loadingDialog != null && !loadingDialog.isShowing()) {
            loadingDialog.show();
            if (loadingAnim != null) {
                loadingAnim.start();
            }
        }
    }

    public LoadingDialog(Context context) {
        DirectionalLayout layout = (DirectionalLayout) LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_loading, null, false);
        layout.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (loadingDialog != null && loadingDialog.isShowing()) {
                    loadingDialog.hide();
                }
            }
        });
        Component component = layout.findComponentById(ResourceTable.Id_cp_loading_anim);
        loadingAnim = ((FrameAnimationElement) component.getBackgroundElement());
        loadingDialog = (CommonDialog) new CommonDialog(context)
                .setContentCustomComponent(layout)
                .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT
                        , DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                .setDuration(Integer.MAX_VALUE)
                .setAlignment(LayoutAlignment.CENTER)
                .setTransparent(true);
        loadingDialog.setDestroyedListener(new CommonDialog.DestroyedListener() {
            @Override
            public void onDestroy() {
                if (loadingAnim != null) {
                    loadingAnim.stop();
                    loadingAnim.release();
                }
            }
        });
    }

    public void hide() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.hide();
            if (loadingAnim != null) {
                loadingAnim.stop();
            }
        }
    }

    public boolean isShowing() {
        return loadingDialog != null && loadingDialog.isShowing();
    }
}
